import _axios from "axios";
// import store from "@/store";
// import reqstatus from "@/utils/requestStatus";

const axios = _axios.create({
  baseURL: "https://java.cx-tidc.com/manage",
  // baseURL: "//10.0.19.140:8080/manage",
  timeout: 1000,
  // withCredentials: true,
  retry: 3,
  retryDelay: 800,
});

axios.interceptors.response.use(
  undefined,
  error => {
    // 服务器存在response并返回了code，进行全局错误处理
    if (error.response) {
      switch (error.response.data.code) {
        default:
          return Promise.reject(error);
      }
    }

    // 服务器没response，说明请求超时或服务器炸了，尝试重新发起请求
    let config = error.config;

    if (!config || !config.retry) return Promise.reject(error);
    config.__retryCount = config.__retryCount || 0;

    if (config.__retryCount >= config.retry) {
      return Promise.reject(error);
    }

    config.__retryCount += 1;

    let backoff = new Promise(function (resolve) {
      setTimeout(function () {
        resolve();
      }, config.retryDelay || 1);
    });

    return backoff.then(function () {
      return axios(config);
    });
  }
);

const api = {
  submitApplyForm(data) {
    return ajax("application-form/", "post", {
      data
    });
  },

};
export default api;

/**
 * @param url
 * @param method get|post|put|delete...
 * @param params like queryString. if a url is index?a=1&b=2, params = {a: '1', b: '2'}
 * @param data post data, use for method put|post
 * @returns {Promise}
 */
function ajax(url, method, options) {
  let params = {}, data = {};
  if (options !== undefined) {
    params = options.params || {};
    data = options.data || {};
  } else {
    params = data = {};
  }
  // if (store.getters.hasToken && url.indexOf("logout") === -1) {
  //   params["access_token"] = data["access_token"] = store.getters.accessToken;
  // }

  return new Promise((resolve, reject) => {
    axios({
      url,
      method,
      params,
      data,
    }).then((res) => {
      // if (res.data.status === reqstatus.FAILED) {
      //   reject(res);
      // } else {
      resolve(res);
      // }
    }, (error) => {
      reject(error);
    });
  });
}
